﻿// --------------------------------
// <copyright file="Defaults.cs" company="Faculty of Information Technology, Czech Technical University in Prague">
//     This document is shared by Microsoft Public License (MS-PL)
//     For further details please see http://msdn.microsoft.com/en-us/library/ff648068.aspx or license.txt.
// </copyright>
// <author>Lukáš Molnár</author>

// <email>molnaluk@fit.cvut.cz</email>

// <date>22. 11. 2011 23:09:43</date>

// <summary>
//
// </summary>
// --------------------------------

using System.IO;
using System.IO.IsolatedStorage;
using Microsoft.Xna.Framework;

namespace FITClub.Episode1.Defaults
{
    internal class Defaults
    {
        public static void CopyFile(Stream fsIn, Stream fsOut)
        {
            byte[] buffer = new byte[4096];
            int r = fsIn.Read(buffer, 0, buffer.Length);
            while (r > 0)
            {
                fsOut.Write(buffer, 0, r);
                r = fsIn.Read(buffer, 0, buffer.Length);
            }
        }

        public static void CopyFile(string local, string isolated, IsolatedStorageFile storage)
        {
            using (Stream fs = TitleContainer.OpenStream(local))
            using (IsolatedStorageFileStream iss = storage.OpenFile(isolated, FileMode.Create, FileAccess.Write))
            {
                CopyFile(fs, iss);
            }
        }

        /// <summary>
        /// Copy file into isolated storage, if does not exist
        /// </summary>
        /// <param name="local"></param>
        /// <param name="isolated"></param>
        /// <param name="storage"></param>
        public static void CopyIfNotExists(string local, string isolated, IsolatedStorageFile storage)
        {
            string dir = Path.GetDirectoryName(isolated);
            if (storage.DirectoryExists(dir) == false)
            {
                storage.CreateDirectory(dir);
            }
            if (storage.FileExists(isolated) == false)
            {
                CopyFile(local, isolated, storage);
            }
        }

        /// <summary>
        /// Deploys defaults into isolated storage.
        /// </summary>
        public static void Deploy()
        {
#if WINDOWS
            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForDomain())
#else
            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())            //.GetUserStoreForDomain()
#endif
            {
#if WINDOWS_PHONE
                string[] files = { @"Menu\OptionsMenu.xml" };
#else
                string[] files = { @"Menu\OptionsMenu.xml", @"Defaults\Player 1.controls", @"Defaults\Player 2.controls", @"Defaults\Player 3.controls" };
#endif
                foreach (var item in files)
                {
                    CopyIfNotExists(item, item, storage);
                }
            }
        }
    }
}